<template>
  <div id="app">
    <el-container>
      <el-header class="header">
        <div class="header-content">
          <div class="logo">
            <img src="https://www.wanandroid.com/resources/image/pc/logo.png" alt="">
          </div>
          <nav>
            <router-link v-for="(item, idx) in navList" :key="idx" :to="item.href">{{item.title}}</router-link>

            <router-link v-if="$store.state.user.isLogin==='ok'" to="/collection" key="collection">收藏</router-link>
          </nav>
          <div class="userMsg">
            <p v-if="$store.state.user.isLogin==='ok'">
              <span>{{username}}</span>
              <span @click="exit()">退出</span>
            </p>
            <p v-else>
              <span @click="toReg">注册</span>
              <span @click="toLog">登录</span>
            </p>
            <span class="" @click="$router.push('/message').catch(err=>{})">站内信</span>
          </div>
        </div>
      </el-header>
      <el-container class="container">
        <div class="content">
          <el-main class="main">
            <keep-alive>
              <router-view v-if="$route.meta.isKeep" name="main"></router-view>
            </keep-alive>
            <router-view v-if="!$route.meta.isKeep" name="main"></router-view>
          </el-main>
          <el-aside class="aside">
            <router-view name="aside"></router-view>
          </el-aside>
        </div>
      </el-container>
      <el-footer class="footer">Footer</el-footer>
    </el-container>
    <!-- 弹出框，准备用来做登录 或 注册 -->
    <el-dialog :title="logType.title" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item label="用户名" :label-width="formLabelWidth">
          <el-input v-model="form.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth">
          <el-input v-model="form.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="重复密码" :label-width="formLabelWidth" v-if="isReg">
          <el-input v-model="form.password2" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="验证码" :label-width="formLabelWidth" v-if="isReg">
          <el-input v-model="form.checkCode" autocomplete="off"></el-input>
        </el-form-item>
        <p v-if="!isReg">
          忘记密码
          <span @click="toReg">去注册</span>
        </p>
        <p v-if="isReg" @click="toLog">
          去登录
        </p>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="onSubmit">{{logType.title}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getNavData, useUser, logout } from "@/api";
import tools from "@/tools"
import { mapState, mapMutations } from "vuex";

export default {
  data(){
    return {
      navList:[],
      dialogFormVisible: false,
      form: {
        username: '',
        password: '',
        password2: '',
        checkCode: '',
      },
      logType: {
        title: "注册",
        type:"register"
      },
      isReg: true,
      pw: "",
      formLabelWidth: '120px',
    }
  },
  created (){
    getNavData().then(res=>{
      this.navList = res.data;
    })
    // 组件创建之初，应该立即vuex，从vuex中获取用户信息，显示到页面
    // this.username = this.$store.state.user.username;
  },
  mounted(){
  },
  methods: {
    ...mapMutations({
      set_isLogin: "user/set_isLogin",
      set_username: "user/set_username",
      set_password: "user/set_password"
    }),
    toReg(){
      // 显示注册表单
      this.dialogFormVisible = true;
      this.logType.title = "注册";
      this.logType.type = "register";
      this.isReg = true;
      this.clearFormValue();
    },
    toLog(){
      // 显示登录表单
      this.dialogFormVisible = true;
      this.logType.title = "登录";
      this.logType.type = "login";
      this.isReg = false;
      this.clearFormValue();
    },
    onSubmit(){
      // 提交之后的功能
      // 计划在注册成功后，自动登录，所以需要将密码临时存储起来（注册成功后，用户名会自动返回）
      this.pw = this.form.password;

      // 使用平台的登录或注册接口
      useUser(this.logType.type, {
        username: this.form.username,
        password: this.form.password,
        repassword: this.form.password2
      }).then(res=>{
        // 登录或注册完成
        // console.log(res.data);

        // 登录或注册失败
        if(res.data.errorCode === -1){
          // 错误提示
          this.$message.error(res.data.errorMsg);
        }else if(this.logType.type === "login"){
          // 登录成功后要执行的功能
          this.loginSuccess(res.data.data)
        }else if(this.logType.type === "register"){
          // 注册成功后要执行的功能
          this.registerSuccess(res.data.data);
        };
      })

      this.clearFormValue();
    },
    clearFormValue(){
      this.form.username = "";
      this.form.password = "";
      this.form.password2 = "";
      this.form.checkCode = "";
    },
    loginSuccess(data){
      // 隐藏对话框
      this.dialogFormVisible = false;
      // 提示信息
      this.$message({
        message: '恭喜你，登录成功',
        type: 'success'
      });

      const d = new Date();
      d.setDate(d.getDate()+30);
      document.cookie = "isLogin=ok;expires="+d;

      // 登录成功后，将登录成功产生的信心，保存到状态管理器（vuex）中，以便将来在其他组件中使用
      // this.$store.commit("user/set_isLogin", "ok");
      this.set_isLogin("ok");

      // this.$store.commit("user/set_username", data.username);
      this.set_username(data.username);

      // this.$store.commit("user/set_password", tools.getCookie("token_pass"));
      this.set_password(tools.getCookie("token_pass"))

      // 登录成功后，修改视图上的用户名信息
      // this.username = this.$store.state.user.username;
    },
    registerSuccess(data){
      this.dialogFormVisible = false;
      this.$message({
        message: '恭喜你，注册成功',
        type: 'success'
      });
      // 注册成功后，自动登录
      useUser("/login", {
        username: data.username,
        password: this.pw
      }).then(res=>{
        if(res.data.errorCode === -1){
          this.$message.error(res.data.errorMsg);
        }else{
          this.loginSuccess(res.data.data)
        }
      })
    },
    exit(){
      // 调用后端提供的退出接口，执行后端的退出功能
      logout().then(()=>{
        // 退出之后，清除本地前端的相关数据
        // this.$store.commit("user/set_isLogin", "no");
        this.set_isLogin("no");
        // this.$store.commit("user/set_username", "");
        this.set_username("");
        // this.$store.commit("user/set_password", "");
        this.set_password("");
        tools.setCookie("isLogin", "no");

        // 退出之后，回到首页
        this.$router.push("/")
      })
    }
  },
  computed:{
    ...mapState({
      isLogin: state=>state.user.isLogin,
      username: state=>state.user.username
    })
  }
}
</script>

<style lang="less">
html,body,ul,li,p,h1,h2,h3,h4,h5,h6,ol{
  margin:0;padding:0;
}
li{
  list-style:none;
}
em,i{
  font-style:normal;
}
b,strong{
  font-weight:normal;
}
img{
  display:block;
}
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #2c3e50;
  .header{
    border-bottom:solid 2px #eaeaea;
    box-sizing: content-box;
    display:flex;
    align-items:center;
    .header-content{
      display:flex;
      width: 1100px;
      margin:0 auto;
      align-items:center;
      .logo{
        margin-right:20px;
        img{
          width:60px;
        }
      }
      nav{
        display:flex;
        a{
          width: 60px;
          margin:0 10px;
          text-align:center;
          line-height: 56px;
          border-bottom:solid 4px transparent;
          text-decoration: none;
          &:hover{
            border-bottom-color: #00f;
          }
          &.router-link-exact-active{
            border-bottom-color: #00f;
          }
        }
      }
      .userMsg{
        margin-left:auto
      }
    }
  }
  .container{
    background: #efefef;
    .content{
      width:1100px;
      margin:0 auto;
      display: flex;
      .main{
        width:760px;
        padding-left: 0;
        margin-right:40px;
        overflow: initial;
      }
      .aside{
        width:300px;
      }
    }
  }
  .footer{
    height:60px;
    line-height:60px;
    text-align:center;
    background:#eaeaea;
  }
}
</style>
